package com.zzyl.job;

import cn.hutool.core.collection.CollUtil;
import com.zzyl.entity.Contract;
import com.zzyl.enums.ContractStatusEnum;
import com.zzyl.service.ContractService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 合同管理
 *
 * @author itheima
 */
@Slf4j
@Component
public class ContractJob {

    @Resource
    ContractService contractService;

    /**
     * 合同状态更新<br>
     * 每小时执行一次
     */
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void contractJob() {
        //查询出所有待生效状态的合同
        List<Contract> pendingEffectiveList = contractService.listByStatus(ContractStatusEnum.PENDING_EFFECTIVE.getOrdinal());
        if (CollUtil.isNotEmpty(pendingEffectiveList)) {
            //如果当前时间处于合同开始时间和结束时间之间，标记合同已生效
            pendingEffectiveList = pendingEffectiveList.stream()
                    .filter(c -> c.getStartTime().isBefore(LocalDateTime.now()) && c.getEndTime().isAfter(LocalDateTime.now()))
                    .collect(Collectors.toList());

            if (CollUtil.isNotEmpty(pendingEffectiveList)) {
                contractService.updateBatchById(pendingEffectiveList, ContractStatusEnum.EFFECTIVE.getOrdinal());
            }
        }

        //查询出所有生效中状态的合同
        List<Contract> effectiveList = contractService.listByStatus(ContractStatusEnum.EFFECTIVE.getOrdinal());
        if (CollUtil.isNotEmpty(effectiveList)) {
            //如果合同结束时间小于当前时间，标记合同已过期
            effectiveList = effectiveList.stream()
                    .filter(c -> c.getEndTime().isBefore(LocalDateTime.now()))
                    .collect(Collectors.toList());

            if (CollUtil.isNotEmpty(effectiveList)) {
                contractService.updateBatchById(effectiveList, ContractStatusEnum.EXPIRED.getOrdinal());
            }
        }
    }

}
